package agitext

import (
	"encoding/base64"
	"fmt"
	"os"

	"github.com/golang/protobuf/jsonpb"

	pb "atomgit.com/atomgit_dev/satellite-proto/go"
)

const _AgitPbRepositoryEnvKey = "AGIT_PROTO_REPOSITORY"

func GetPbRepositoryFromEnv() (*pb.Repository, error) {
	raw, ok := os.LookupEnv(_AgitPbRepositoryEnvKey)
	if !ok || raw == "" {
		return nil, fmt.Errorf("%s is not set or empty", _AgitPbRepositoryEnvKey)
	}

	rawJson, err := base64.StdEncoding.DecodeString(raw)
	if err != nil {
		return nil, err
	}
	res := &pb.Repository{}
	err = jsonpb.UnmarshalString(string(rawJson), res)
	if err != nil {
		return nil, err
	}

	return res, nil
}
